import argparse, pypdf, re

parser = argparse.ArgumentParser()
parser.add_argument('ipdf')
parser.add_argument('opdf')
parser.add_argument('outline')
args = parser.parse_args()

writer = pypdf.PdfWriter(clone_from=args.ipdf)

page_number = 0
with open(args.outline) as f:
    for row in f:
        row = row[:-1]  # remove newline
        if '' == row:
            page_number += 1
        elif re.match('^\d+$', row):
            page_number = int(row)
        elif re.match('^[^ ]+$', row):
            leimu = writer.add_outline_item(row, page_number)
        elif re.match('^ [^ ]+$', row):
            fenmu = writer.add_outline_item(row[1:], page_number, leimu)
        elif re.match('^  [^ ]+$', row):
            writer.add_outline_item(row[2:], page_number, fenmu)

writer.write(args.opdf)
